package com.example.persion.commmon.expetion;


import com.example.persion.commmon.lang.Result;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


// 根据不同的异常 返回不同的数据处理

@Slf4j
//  都是异步操作 所以选用这个注解
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    //捕获异常
    @ExceptionHandler(value =  IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e ){

        log.error("Assert异常: -------");
        return   Result.fail(e.getMessage());
    }


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    //捕获异常
    @ExceptionHandler(value =  RuntimeException.class)
    public Result handler(RuntimeException e ){

        log.error("运行时 异常: -------");
        return   Result.fail(e.getMessage());
    }


    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    //捕获异常
    @ExceptionHandler(value =  ShiroException.class)
    public Result handler(ShiroException e ){

        log.error("Shiro时 异常: -------");
        return  Result.fail(401,e.getMessage(),null);
    }


    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    //捕获异常
    @ExceptionHandler(value =  MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e ){

        log.error("实体校验异常: -------");

        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();

        return  Result.fail(e.getMessage());
    }


}
